package com.cyclicbarrier;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.StampedLock;

/**
 * 所有线程都调用了await后，才去执行
 */
public class CyclicBarrierDemo {

    public static void main(String[] args) {
        int threadNum = 5;
        ReadWriteLock readWriteLock = new StampedLock().asReadWriteLock();

        CyclicBarrier barrier = new CyclicBarrier(threadNum);
        for (int i = 0; i < threadNum; i++) {
            new TaskThread(barrier).start();
        }
    }

    static class TaskThread extends Thread {

        CyclicBarrier barrier;

        public TaskThread(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);

                System.out.println(getName() + " 到达栅栏 A");
                barrier.await();

                System.out.println(getName() + " 冲破栅栏 A");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
